<?php

namespace app\common\dao\repair;

use think\db\BaseQuery;
use app\common\dao\BaseDao;
use app\common\model\repair\RepairOrderModel;
use app\common\repositories\repair\RepairCateRepository;

class RepairOrderDao extends BaseDao
{

    /**
     * @return RepairOrderModel
     */
    protected function getModel(): string
    {
        return RepairOrderModel::class;
    }


    public function search(array $where, int $propertyId = null)
    {
        return $this->getModel()::getDB()
            ->when($propertyId !== null, function ($query) use ($propertyId) {
                $query->where('property_id', $propertyId);
            })
            ->when(isset($where['cate_id']) && $where['cate_id'] !== '', function ($query) use ($where) {
                $query->where('cate_id', (int)$where['cate_id']);
            })
            ->when(isset($where['user_id']) && $where['user_id'] !== '', function ($query) use ($where) {
                $query->where('user_id', (int)$where['user_id']);
            })
            ->when(isset($where['cates_id']) && $where['cates_id'] !== '', function ($query) use ($where) {
                /** @var RepairCateRepository $repository */
                $repository = app()->make(RepairCateRepository::class);
                $query->where('cate_id', 'in', array_merge([$where['cates_id']], $repository->getChildIds($where['cates_id'])));
            })
            ->when(isset($where['status']) && $where['status'] !== '', function ($query) use ($where) {
                $query->where('status', (int)$where['status']);
            })
            ->when(isset($where['keywords']) && $where['keywords'] !== '', function ($query) use ($where) {
                $query->whereLike('content', '%' . trim($where['keywords']) . '%');
            })
            ->when(isset($where['add_time']) && $where['add_time'] !== '', function ($query) use ($where) {
                $this->timeSearchBuild($query, $where['add_time'], 'add_time');
            });
    }


    /**
     * 工单编号是否存在
     * @param string $assetNo 资产编号
     * @param int|null $propertyId 企业ID
     * @return bool
     * @throws \think\db\exception\DbException
     */
    public function repairNoExists(string $assetNo, ?int $propertyId = null)
    {
        return $this->getSearch([])
                ->where('repair_no', $assetNo)
                ->when($propertyId !== null, function ($query) use ($propertyId) {
                    $query->where('property_id', $propertyId);
                })->count() > 0;
    }
}
